
#Shibboleth authentication. 
module Shibboleth

  #If user is authenticated calls the block with users' data.
  def self.authenticate request
    unless Shibboleth.enabled
      return false
    end
    
    a = Authentication.new request
    if a.anonymous? 
      return false
    end
    yield a.user
  end
  
  #factory method
  def self.authentication request
    Authentication.new request
  end
  
  class Authentication
  
    FIELD_PERSISTENT_ID = 'field_persistent_id:'
    FIELD_UNIQUE_ID = 'field_unique_id:'
    FIELD_LOGIN_ID = 'login_id'
    FIELD_FIRSTNAME = 'field_firstname'
    FIELD_LASTNAME = 'field_lastname'
    FIELD_EMAIL = 'field_email'
    FIELD_LANGUAGE = 'field_language'
    FIELD_GENDER = 'field_gender'
    FIELD_ADDRESS = 'field_address'
    FIELD_STAFF_CATEGORY = 'field_staf_category'
    FIELD_HOME_ORGANIZATION_TYPE = 'field_home_organization_type'
    FIELD_HOME_ORGANIZATION = 'field_home_organization'
    FIELD_AFFILIATION = 'field_affiliation'   
    
    def initialize request
      @request = request
    end
    
    def request
      @request
    end
  
    #Returns authenticated user's data. If not authenticated returns an empty hash
    #Returns a hash
    def user
      if anonymous? 
        return {}
      end
      result = {}
      Shibboleth::settings.each do |k,v|         
        result[k] = request.headers[v] if request.headers.include?(v)
      end
      return result
    end
  
    #Returns true if user is anonymous. False otherwise
    def anonymous?
      key = Shibboleth::settings[FIELD_LOGIN_ID]
      if ! request.headers.has_key?(key)
        return true
      end
      request.headers[key].blank?
    end
  
    #True if user is authenticated. False Otherwise.
    def authenticated?
      ! anonymous?
    end
  
  end
  
end